package com.rtsapp.server.utils;

public class TimestampUtils {

	public static String encrypt(int userId, long currentTimeMillis, String key) {
		String str = null;
		str = AESUtils.encrypt(NumberUtils.parseByte2HexStr(NumberUtils
				.parseLong2bytes(currentTimeMillis)), String.valueOf(userId));
		str = AESUtils.encrypt(str, key);

		return str;
	}

	public static boolean decrypt(int uniquelyId, String timestamp, String key,
			int tolerantTime, int timeout) {
		String str;
		str = AESUtils.decrypt(timestamp, key);
		str = AESUtils.decrypt(str, String.valueOf(uniquelyId));
		if (str == null) {
			return false;
		}
		long time = NumberUtils.parseBytes2long(NumberUtils.parseHexStr2Byte(str));
		long currentTime = System.currentTimeMillis();
		long subTime = currentTime - time;
		if (subTime > -tolerantTime * 1000 && subTime < timeout * 1000) {
			return true;
		}
		return false;
	}

	public static String encrypt(int serverId, int playerId,
			long currentTimeMillis, String key) {
		String str = null;
		str = AESUtils.encrypt(NumberUtils.parseByte2HexStr(NumberUtils
				.parseLong2bytes(currentTimeMillis)), String.valueOf(playerId));
		str = AESUtils.encrypt(str, String.valueOf(serverId));
		str = AESUtils.encrypt(str, key);

		return str;
	}

	public static boolean decrypt(int serverId, int playerId, String timestamp,
			String key, int tolerantTime, int timeout) {
		String str = null;
		str = AESUtils.decrypt(timestamp, key);
		str = AESUtils.decrypt(str, String.valueOf(serverId));
		str = AESUtils.decrypt(str, String.valueOf(playerId));
		long time = NumberUtils.parseBytes2long(NumberUtils
				.parseHexStr2Byte(str));
		long currentTime = System.currentTimeMillis();
		long subTime = currentTime - time;
		if (subTime > -tolerantTime * 1000 && subTime < timeout * 1000) {
			return true;
		}
		return false;
	}
}
